<template>
  <view class="container">
    <!-- 贷款计算表单 -->
    <view class="form-section">
      <view class="section-title">贷款信息</view>
      <view class="form-item">
        <text>贷款类型：</text>
        <picker :range="loanTypeList" @change="onLoanTypeChange">
          <view class="picker">{{ loanTypeList[form.loanType] }}</view>
        </picker>
      </view>

      <!-- 商贷 / 公积金贷款 -->
      <view v-if="form.loanType === 0 || form.loanType === 1">
        <view class="form-item">
          <text>贷款金额（元）：</text>
          <input v-model.number="form.amount" placeholder="请输入贷款金额" />
        </view>
        <view class="form-item">
          <text>贷款利率（%）：</text>
          <input v-model.number="form.rate" placeholder="请输入年利率，如4.9" />
        </view>
      </view>

      <!-- 组合贷款 -->
      <view v-if="form.loanType === 2">
        <view class="form-item">
          <text>商业贷款金额（元）：</text>
          <input v-model.number="form.businessAmount" placeholder="请输入商贷金额" />
        </view>
        <view class="form-item">
          <text>商业贷款利率（%）：</text>
          <input v-model.number="form.businessRate" placeholder="请输入商贷年利率" />
        </view>
        <view class="form-item">
          <text>公积金贷款金额（元）：</text>
          <input v-model.number="form.providentAmount" placeholder="请输入公积金金额" />
        </view>
        <view class="form-item">
          <text>公积金贷款利率（%）：</text>
          <input v-model.number="form.providentRate" placeholder="请输入公积金利率" />
        </view>
      </view>

      <!-- 通用字段 -->
      <view class="form-item">
        <text>贷款期限：</text>
        <input v-model.number="form.years" placeholder="如30年、3个月=0.25年、6个月=0.5年" />
      </view>
      <view class="form-item">
        <text>还款方式：</text>
        <picker :range="repaymentTypes" @change="onRepaymentTypeChange">
          <view class="picker">{{ repaymentTypes[form.repaymentType] }}</view>
        </picker>
      </view>

      <button type="primary" @click="onCalculate" :disabled="loading" class="calc-btn">
        {{ loading ? '计算中...' : '开始计算' }}
      </button>
    </view>

    <!-- 计算结果总览 -->
    <view v-if="result" class="result-section">
      <view class="section-title">计算结果总览</view>
      <view class="result-grid">
        <view class="result-item">
          <text class="label">月供</text>
          <text class="value">¥{{ formatAmount(result.monthlyPayment) }}</text>
        </view>
        <view class="result-item">
          <text class="label">贷款金额</text>
          <text class="value">¥{{ formatAmount(getLoanAmount()) }}</text>
        </view>
        <view class="result-item">
          <text class="label">贷款期限</text>
          <text class="value">{{ formatLoanPeriod() }}</text>
        </view>
        <view class="result-item">
          <text class="label">年利率</text>
          <text class="value">{{ getAverageRate() }}%</text>
        </view>
        <view class="result-item">
          <text class="label">总利息</text>
          <text class="value">¥{{ formatAmount(result.totalInterest) }}</text>
        </view>
        <view class="result-item">
          <text class="label">总支付金额</text>
          <text class="value">¥{{ formatAmount(result.totalRepayment) }}</text>
        </view>
        <view class="result-item">
          <text class="label">贷款类型</text>
          <text class="value">{{ loanTypeList[form.loanType] }}</text>
        </view>
        <view class="result-item">
          <text class="label">还款方式</text>
          <text class="value">{{ repaymentTypes[form.repaymentType] }}</text>
        </view>
        <view class="result-item" v-if="form.repaymentType === 1 && getDecreaseAmount() > 0">
          <text class="label">递减数值</text>
          <text class="value">¥{{ formatAmount(getDecreaseAmount()) }}</text>
        </view>
      </view>
    </view>

    <!-- 统计图表 -->
    <view v-if="result && monthlyDetails.length" class="chart-section">
      <view class="section-title">统计图表</view>
      
      <!-- 贷款金额与总利息对比 -->
      <view class="chart-container">
        <view class="chart-title">贷款金额 vs 总利息</view>
        <view class="chart-bars">
          <view class="bar-item">
            <view class="bar" :style="{ height: getBarHeight(getLoanAmount(), getMaxAmount()) + 'rpx' }">
              <text class="bar-label">贷款金额</text>
            </view>
            <text class="bar-value">¥{{ formatAmount(getLoanAmount()) }}</text>
          </view>
          <view class="bar-item">
            <view class="bar interest-bar" :style="{ height: getBarHeight(result.totalInterest, getMaxAmount()) + 'rpx' }">
              <text class="bar-label">总利息</text>
            </view>
            <text class="bar-value">¥{{ formatAmount(result.totalInterest) }}</text>
          </view>
        </view>
      </view>

      <!-- 贷款构成分析 -->
      <view class="chart-container">
        <view class="chart-title">贷款构成分析</view>
        <view class="pie-chart-container">
          <view class="pie-chart" :style="{ background: `conic-gradient(#007aff 0deg ${getLoanAmountAngle()}deg, #ff9500 ${getLoanAmountAngle()}deg ${getLoanAmountPlusInterestAngle()}deg, #28a745 ${getLoanAmountPlusInterestAngle()}deg 360deg)` }">
            <view class="pie-center">
              <text class="center-text">总支付</text>
              <text class="center-amount">¥{{ formatAmount(result.totalRepayment) }}</text>
            </view>
          </view>
        </view>
        <view class="pie-legend">
          <view class="legend-item">
            <view class="legend-color principal"></view>
            <text>本金: ¥{{ formatAmount(getLoanAmount()) }} ({{ getPrincipalTotalPercentage().toFixed(1) }}%)</text>
          </view>
          <view class="legend-item">
            <view class="legend-color interest"></view>
            <text>利息: ¥{{ formatAmount(result.totalInterest) }} ({{ getInterestTotalPercentage().toFixed(1) }}%)</text>
          </view>
          <view class="legend-item">
            <view class="legend-color total"></view>
            <text>总支付: ¥{{ formatAmount(result.totalRepayment) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 每月还款明细 -->
    <view v-if="monthlyDetails && monthlyDetails.length" class="details-section">
      <view class="section-title">每月还款明细</view>
      
      <!-- 明细表格 -->
      <view class="details-table">
        <view class="table-header">
          <text class="col col-m">期数</text>
          <text class="col">月供</text>
          <text class="col">本金</text>
          <text class="col">利息</text>
          <text class="col">剩余本金</text>
        </view>
        <view v-for="item in monthlyDetails" :key="item.monthIndex" class="table-row">
          <text class="col col-m">{{ item.monthIndex }}</text>
          <text class="col">¥{{ formatAmount(item.totalPayment) }}</text>
          <text class="col">¥{{ formatAmount(item.principal) }}</text>
          <text class="col">¥{{ formatAmount(item.interest) }}</text>
          <text class="col">¥{{ formatAmount(item.remainingPrincipal) }}</text>
        </view>
      </view>

      <!-- 分页加载 -->
      <view class="pager" v-if="currentPage < totalPages">
        <button type="default" @click="loadMore" :disabled="loadingMore" class="load-more-btn">
          {{ loadingMore ? '加载中...' : '加载更多' }}
        </button>
      </view>
      <view class="pager" v-else>
        <text class="pager-info">已加载全部 {{ totalMonths }} 期数据</text>
      </view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
      loanTypeList: ['商业贷款', '公积金贷款', '组合贷款'],
      repaymentTypes: ['等额本息', '等额本金'],
      form: {
        loanType: 0,
        repaymentType: 0,
        amount: null,
        rate: null,
        businessAmount: null,
        businessRate: null,
        providentAmount: null,
        providentRate: null,
        years: 30
      },
      result: null,
      // 分页相关
      currentPage: 1,
      pageSize: 12,
      totalPages: 0,
      totalMonths: 0,
      monthlyDetails: [],
      // 状态
      loading: false,
      loadingMore: false,
      baseUrl: 'http://localhost:8080'
    };
		},
		methods: {
    formatAmount(value) {
      const n = Number(value);
      if (isNaN(n)) return '0.00';
      return n.toFixed(2);
    },
    onLoanTypeChange(e) {
      this.form.loanType = Number(e.detail.value);
    },
    onRepaymentTypeChange(e) {
      this.form.repaymentType = Number(e.detail.value);
    },
    buildPayload() {
      return {
        loanType: this.loanTypeList[this.form.loanType],
        repaymentType: this.repaymentTypes[this.form.repaymentType],
        years: this.form.years,
        amount: this.form.amount,
        rate: this.form.rate,
        businessAmount: this.form.businessAmount,
        businessRate: this.form.businessRate,
        providentAmount: this.form.providentAmount,
        providentRate: this.form.providentRate,
      };
    },
    getLoanAmount() {
      if (this.form.loanType === 2) {
        return (this.form.businessAmount || 0) + (this.form.providentAmount || 0);
      }
      return this.form.amount || 0;
    },
    getAverageRate() {
      if (this.form.loanType === 2) {
        const businessAmount = this.form.businessAmount || 0;
        const providentAmount = this.form.providentAmount || 0;
        const totalAmount = businessAmount + providentAmount;
        if (totalAmount === 0) return 0;
        return (((businessAmount * (this.form.businessRate || 0)) + (providentAmount * (this.form.providentRate || 0))) / totalAmount).toFixed(2);
      }
      return this.form.rate || 0;
    },
    getDecreaseAmount() {
      // 等额本息没有递减，等额本金才有递减
      if (this.form.repaymentType === 0) {
        return 0; // 等额本息，月供固定，无递减
      }
      
      // 等额本金，计算递减数值
      if (this.form.repaymentType === 1 && this.monthlyDetails.length >= 2) {
        const firstMonth = this.monthlyDetails[0].totalPayment;
        const secondMonth = this.monthlyDetails[1].totalPayment;
        const decrease = firstMonth - secondMonth;
        
        // 验证数据合理性：递减值应该等于月利率 × 月供本金
        const monthlyRate = (this.getAverageRate() / 100) / 12;
        const monthlyPrincipal = this.monthlyDetails[0].principal;
        const expectedDecrease = monthlyPrincipal * monthlyRate;
        
        // 如果差异太大，返回0（可能是数据问题）
        if (Math.abs(decrease - expectedDecrease) > 0.01) {
          console.warn('递减数值异常，预期:', expectedDecrease, '实际:', decrease);
          return 0;
        }
        
        return decrease;
      }
      return 0;
    },
    getMaxAmount() {
      return Math.max(this.getLoanAmount(), this.result?.totalInterest || 0);
    },
    getBarHeight(value, maxValue) {
      if (maxValue === 0) return 0;
      return (value / maxValue) * 200; // 最大高度200rpx
    },
    getFirstMonthPrincipal() {
      return this.monthlyDetails[0]?.principal || 0;
    },
    getFirstMonthInterest() {
      return this.monthlyDetails[0]?.interest || 0;
    },
    getPrincipalPercentage() {
      const principal = this.getFirstMonthPrincipal();
      const total = this.result?.monthlyPayment || 1;
      if (total === 0) return 0;
      return (principal / total) * 100;
    },
    getInterestPercentage() {
      const interest = this.getFirstMonthInterest();
      const total = this.result?.monthlyPayment || 1;
      if (total === 0) return 0;
      return (interest / total) * 100;
    },
    getPrincipalAngle() {
      const percentage = this.getPrincipalPercentage();
      return (percentage / 100) * 360;
    },
    getInterestAngle() {
      const percentage = this.getInterestPercentage();
      return (percentage / 100) * 360;
    },
    getLoanAmountAngle() {
      const principal = this.getLoanAmount();
      const totalRepayment = this.result?.totalRepayment || 1;
      if (totalRepayment === 0) return 0;
      return (principal / totalRepayment) * 360;
    },
    getLoanAmountPlusInterestAngle() {
      const principal = this.getLoanAmount();
      const interest = this.result?.totalInterest || 0;
      const totalRepayment = this.result?.totalRepayment || 1;
      if (totalRepayment === 0) return 0;
      return ((principal + interest) / totalRepayment) * 360;
    },
    getPrincipalTotalPercentage() {
      const principal = this.getLoanAmount();
      const totalRepayment = this.result?.totalRepayment || 1;
      if (totalRepayment === 0) return 0;
      return (principal / totalRepayment) * 100;
    },
    getInterestTotalPercentage() {
      const interest = this.result?.totalInterest || 0;
      const totalRepayment = this.result?.totalRepayment || 0;
      if (totalRepayment === 0) return 0;
      return (interest / totalRepayment) * 100;
    },
    getYAxisLabels() {
      if (!this.monthlyDetails.length) return [];
      const maxAmount = Math.max(
        ...this.monthlyDetails.map(item => item.totalPayment),
        ...this.monthlyDetails.map(item => item.principal),
        ...this.monthlyDetails.map(item => item.interest)
      );
      const step = maxAmount / 4;
      return [
        `¥${this.formatAmount(maxAmount)}`,
        `¥${this.formatAmount(maxAmount * 0.75)}`,
        `¥${this.formatAmount(maxAmount * 0.5)}`,
        `¥${this.formatAmount(maxAmount * 0.25)}`,
        '¥0'
      ];
    },
    getXAxisLabels() {
      if (!this.monthlyDetails.length) return [];
      const totalMonths = this.monthlyDetails.length;
      const step = Math.max(1, Math.floor(totalMonths / 5));
      const labels = [];
      for (let i = 0; i <= totalMonths; i += step) {
        if (i === 0) {
          labels.push('开始');
        } else if (i === totalMonths) {
          labels.push(`${totalMonths}期`);
        } else {
          labels.push(`${i}期`);
        }
      }
      return labels;
    },
    getTrendDataPoints() {
      if (!this.monthlyDetails.length) return [];
      // 选择关键时间点的数据：开始、1/4、1/2、3/4、结束
      const totalMonths = this.monthlyDetails.length;
      const keyPoints = [0, Math.floor(totalMonths * 0.25), Math.floor(totalMonths * 0.5), Math.floor(totalMonths * 0.75), totalMonths - 1];
      
      return keyPoints.map(index => {
        if (index === 0) {
          return {
            total: this.monthlyDetails[0]?.totalPayment || 0,
            principal: this.monthlyDetails[0]?.principal || 0,
            interest: this.monthlyDetails[0]?.interest || 0
          };
        }
        return {
          total: this.monthlyDetails[index]?.totalPayment || 0,
          principal: this.monthlyDetails[index]?.principal || 0,
          interest: this.monthlyDetails[index]?.interest || 0
        };
      });
    },

    onCalculate() {
      // 验证贷款期限
      if (this.form.years <= 0) {
        uni.showToast({ title: '请输入有效的贷款期限', icon: 'none' });
        return;
      }
      if (this.form.years > 50) {
        uni.showToast({ title: '贷款期限不能超过50年', icon: 'none' });
        return;
      }
      
      const totalMonths = this.getTotalMonths();
      if (totalMonths <= 0) {
        uni.showToast({ title: '请输入有效的贷款期限', icon: 'none' });
        return;
      }
      if (totalMonths > 600) { // 最多50年
        uni.showToast({ title: '贷款期限不能超过50年', icon: 'none' });
        return;
      }
      
      this.loading = true;
      this.monthlyDetails = [];
      this.currentPage = 1;
      this.totalPages = 0;
      this.totalMonths = 0;

      uni.request({
        url: `${this.baseUrl}/api/loan/calculate`,
        method: 'POST',
        data: this.buildPayload(),
        success: (res) => {
          this.result = res.data;
          // 成功后加载第一页明细
          this.fetchMonthlyDetails(1);
        },
        fail: () => {
          uni.showToast({ title: '计算失败', icon: 'none' });
        },
        complete: () => {
          this.loading = false;
        },
      });
    },
    fetchMonthlyDetails(page) {
      this.loadingMore = true;
      uni.request({
        url: `${this.baseUrl}/api/loan/monthly-details?page=${page}&size=${this.pageSize}`,
        method: 'POST',
        data: this.buildPayload(),
        success: (res) => {
          const data = res.data || {};
          const list = data.monthlyDetails || [];
          this.currentPage = data.currentPage || page;
          this.totalPages = data.totalPages || 0;
          this.totalMonths = data.totalMonths || 0;
          this.monthlyDetails = this.monthlyDetails.concat(list);
          this.$nextTick(() => {
            // 图表相关方法已删除
          });
        },
        fail: () => {
          uni.showToast({ title: '加载明细失败', icon: 'none' });
        },
        complete: () => {
          this.loadingMore = false;
        },
      });
    },
    loadMore() {
      if (this.currentPage >= this.totalPages) return;
      this.fetchMonthlyDetails(this.currentPage + 1);
    },
    getTotalMonths() {
      return Math.round(this.form.years * 12);
    },
    formatLoanPeriod() {
      const years = this.form.years;
      if (years === 0) {
        return '0年';
      }
      
      // 处理小数年限，转换为年+月的显示
      if (years < 1) {
        const months = Math.round(years * 12);
        return `${months}个月`;
      } else if (years === Math.floor(years)) {
        // 整数年
        return `${years}年`;
      } else {
        // 小数年，转换为年+月
        const wholeYears = Math.floor(years);
        const remainingMonths = Math.round((years - wholeYears) * 12);
        let period = `${wholeYears}年`;
        if (remainingMonths > 0) {
          period += `${remainingMonths}月`;
        }
        return period;
      }
    }
  },
  mounted() {
    // 图表相关方法已删除
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin: 20rpx 0;
  padding-left: 20rpx;
  border-left: 8rpx solid #007aff;
}

.form-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.form-item text {
  min-width: 200rpx;
  font-size: 28rpx;
  color: #333;
}

.picker {
  flex: 1;
  padding: 15rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  background: #fafafa;
}

.calc-btn {
  width: 100%;
  margin-top: 20rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
}

.result-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.result-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.result-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.result-item .label {
  font-size: 24rpx;
  color: #6c757d;
  margin-bottom: 8rpx;
}

.result-item .value {
  font-size: 28rpx;
  font-weight: bold;
  color: #007aff;
}

.chart-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.chart-container {
  margin-bottom: 40rpx;
}

.chart-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  text-align: center;
}

.chart-bars {
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  height: 240rpx;
  padding: 20rpx 0;
}

.bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120rpx;
}

.bar {
  width: 80rpx;
  background: linear-gradient(to top, #007aff, #5ac8fa);
  border-radius: 8rpx 8rpx 0 0;
  position: relative;
  min-height: 20rpx;
}

.interest-bar {
  background: linear-gradient(to top, #ff9500, #ffcc02);
}

.bar-label {
  position: absolute;
  top: -30rpx;
  left: 50%;
  transform: translateX(-50%);
  font-size: 20rpx;
  color: #666;
  white-space: nowrap;
}

.bar-value {
  margin-top: 10rpx;
  font-size: 22rpx;
  color: #333;
  text-align: center;
}

.pie-chart-container {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin: 0 auto 20rpx;
}

.pie-chart {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  position: relative;
  box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.3);
}

.pie-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
  background: white;
  border-radius: 50%;
  width: 120rpx;
  height: 120rpx;
  box-shadow: inset 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.center-text {
  font-size: 20rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.center-amount {
  font-size: 24rpx;
  font-weight: bold;
  color: #007aff;
}

.pie-legend {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
  margin-top: 20rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 15rpx;
  justify-content: center;
}

.legend-color {
  width: 24rpx;
  height: 24rpx;
  border-radius: 4rpx;
}

.legend-color.principal {
  background: #007aff;
}

.legend-color.interest {
  background: #ff9500;
}

.legend-color.total {
  background: #28a745;
}



.details-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.details-table {
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  overflow: hidden;
}

.table-header, .table-row {
  display: flex;
  border-bottom: 1rpx solid #e0e0e0;
}

.table-header {
  background: #f8f9fa;
  font-weight: bold;
}

.table-row:last-child {
  border-bottom: none;
}

.col {
  flex: 1;
  padding: 20rpx 10rpx;
  text-align: center;
  font-size: 24rpx;
  border-right: 1rpx solid #e0e0e0;
}

.col:last-child {
  border-right: none;
}

.col-m {
  width: 100rpx;
  flex: 0 0 100rpx;
}

.pager {
  margin-top: 30rpx;
		display: flex;
		justify-content: center;
	}

.load-more-btn {
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.pager-info {
  color: #6c757d;
  font-size: 26rpx;
}

</style>
